// pages/mine/lingshi_order/lingshi_order.js
var App = getApp();
var hasData = true;
var stopTouch = true;
var cloudPage = 1;//云库商城开始页数
var remainMoney = 0;//使用余额
var orderNumber = '';//要支付的订单编号
var sendOrderNo = '';//确认送达订单号
Page({

  /**
   * 页面的初始数据
   */
  data: {
    contentDis:false,
    cloudList: [],
    noData: true,
    cloudColumn: ['全部','待付款', '待发货', '待收货', '已完成'],
    currentTabSub: 0,
    paymentBlock: false,
    orderMoney: '0.00', //订单金额
    accountMoney: '0.00', //余额
    payChecked: false,
    orderStatus: '',
    showConfirm: false //显示确认收货弹窗
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      currentTabSub: 0
    })
    cloudPage = 1;
    this.getCloudList();
  },

  //云库状态导航切换
  swichCloudStatus: function (e) {
    var index = e.currentTarget.dataset.current;
    cloudPage = 1;
    this.setData({
      currentTabSub: index,
      cloudList: []
    })
    wx.showLoading({
      title: '加载中',
    })
    this.getCloudList();
    stopTouch = false;
  },

  onShow: function () {

  },
  onHide: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (hasData) {
      cloudPage++
      this.getCloudList();
    }

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
 
  // 订单详情
  goOrderDetail: function (e) {
    let no = e.currentTarget.dataset.no;
    wx.navigateTo({
      url: 'lingshi_detail?source=list&type=' + this.data.currentTabSub + '&order_no=' + no,
    })
  },

  //获取云库商城列表
  getCloudList: function () {
    let that = this;
    let maxLength = 10;
    let statusIndex =0;
    switch (that.data.currentTabSub){
      case 0:
        statusIndex='';
        break;
      case 1:
        statusIndex = 0;
        break;
      case 2:
        statusIndex = 4;
        break;
      case 3:
        statusIndex = 1;
        break;
      case 4:
        statusIndex = 2;
        break;
      default:
    }
    wx.request({
      url: App.data.globalAPI + '/order/mall/getlist',
      data: {
        token: wx.getStorageSync('token'),
        page: cloudPage,
        length: maxLength,
        status: statusIndex
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        stopTouch = true;
        if (res.data.error == 0) {
          wx.hideLoading();
          let originList = that.data.cloudList;
          let data = res.data.data;
          if (data.length > 0) { 
            originList.push(...data);
            for (var j = 0; j < originList.length; j++) {
              originList[j].all_number = 0;
              for (var i = 0; i < originList[j].goods.length; i++) {
                originList[j].all_number += parseInt(originList[j].goods[i].number);
              }
            }
            that.setData({
              cloudList: originList,
              contentDis: false,
            })
          } else {
            that.setData({  
              contentDis: true
            })
          }
          if (data.length < maxLength) {
            hasData = false;
          }else{
            hasData = true;
          }
          if (that.data.cloudList.length == 0) {
            that.setData({
              noData: true
            })
          } else {
            that.setData({
              noData: false
            })
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 800
          })
        }
      }, fail() {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  // 取消订单
  onCancelOrder: function (e) {
    let order_no = e.currentTarget.dataset.no;
    let that = this;
    wx.showModal({
      title: '确认提示',
      content: '是否确认取消订单？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: App.data.globalAPI + '/order/mall/cancel',
            data: {
              token: wx.getStorageSync('token'),
              order_no: order_no,
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            success(res) {
              if (res.data.error == 0) {
                wx.showToast({
                  title: '订单取消成功!',
                  duration: 800
                })
                that.setData({
                  cloudList: []
                })
                wx.showLoading({
                  title: '加载中',
                })
                that.getCloudList();
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 800
                })
              }
            }
          })
        } 
      }
    })
  },

  // 关闭支付弹窗
  hidePayModal: function () {
    this.setData({
      paymentBlock: false,
      payChecked: false
    })
  },

  //余额开关
  aliPaySwitch: function () {
    if (this.data.accountMoney == 0) {
      return false;
    }
    this.setData({
      payChecked: !this.data.payChecked
    })

    let orderMoney = this.data.orderMoney;//订单金额
    let yueMoney = this.data.accountMoney;//账户余额

    if (this.data.payChecked) {//使用余额
      if (parseFloat(yueMoney) > orderMoney) {
        remainMoney = parseFloat(orderMoney);
        orderMoney = 0;
      } else {
        remainMoney = yueMoney;
        orderMoney = parseFloat(orderMoney) - parseFloat(yueMoney);
      }
    } else {
      remainMoney = 0;
      orderMoney = parseFloat(this.data.totalAmount);
    }
    this.setData({
      orderMoney: parseFloat(orderMoney).toFixed(2)
    })
  },

  //提交支付
  payMethod: function () {
    let that = this;
    let payWay = '';
    let useYue = 0;//使用的余额
    if (that.data.payChecked && that.data.accountMoney > 0 && that.data.orderMoney == 0) {
      payWay = 'account';
    } else if (that.data.payChecked && that.data.accountMoney > 0 && that.data.orderMoney > 0) {
      payWay = 'mixed';
    } else if (that.data.orderMoney == 0) {
      payWay = 'account';
    } else {
      payWay = 'online';
    }

    wx.request({
      url: App.data.globalAPI + '/order/mall/pay',
      data: {
        token: wx.getStorageSync('token'),
        pay_type: payWay,//在线支付: online 余额支付: account 混合支付: mixed,
        pay_method: payWay == 'account' ? 'account' : 'wxlite',
        order_no: orderNumber,
        pay: parseFloat(that.data.totalAmount).toFixed(2), //实付款
        account_pay: remainMoney,//余额支付金额 
        online_pay: that.data.orderMoney,//在线支付金额 
        client_type: 'wxlite'
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          var payArr = res.data.data.pay;
          var orderArr = res.data.data.order;
          if (payWay == 'account') {
            wx.showToast({
              title: '支付成功！'
            })
            that.setData({
              paymentBlock: false,
              payChecked: false,
              cloudList: []
            })
            that.getCloudList();
            App.getTokenLogin();//更新用户信息
            return false;
          }
          wx.requestPayment({
            timeStamp: payArr.timeStamp,
            nonceStr: payArr.nonceStr,
            package: payArr.package,
            signType: payArr.signType,
            paySign: payArr.paySign,
            success(res) {
              that.setData({
                paymentBlock: false,
                payChecked: false
              })
              that.setData({
                cloudList: []
              })
              that.getCloudList();
              App.getTokenLogin();//更新用户信息
            },
            fail(res) {
              wx.showToast({
                icon: 'none',
                title: '支付已取消'
              })
              that.setData({
                paymentBlock: false
              })
            }
          })
        }
        else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }

      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  //钱包金额
  getMoneyTotal: function () {
    wx.showLoading({
      title: '加载中',
    })
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/wallet/info',
      data: {
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          that.setData({
            accountMoney: parseFloat(res.data.data.money).toFixed(2)
          })
          if (that.data.accountMoney>0){
            that.setData({
              payChecked:true
            })
            let orderMoney = that.data.orderMoney;//订单金额
            let yueMoney = that.data.accountMoney;//账户余额
            if (parseFloat(yueMoney) > orderMoney) {
              remainMoney = parseFloat(orderMoney);
              orderMoney = 0;
            } else {
              remainMoney = yueMoney;
              orderMoney = parseFloat(orderMoney) - parseFloat(yueMoney);
            }
            that.setData({
              orderMoney: parseFloat(orderMoney).toFixed(2)
            })
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
        wx.hideLoading();
      },
      fail(res) {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  //继续支付
  goOnpayOrder: function (e) {
    orderNumber = e.currentTarget.dataset.no;
    this.setData({
      payChecked: true,
      paymentBlock: true,
      orderMoney: parseFloat(e.currentTarget.dataset.pay).toFixed(2),
      totalAmount: parseFloat(e.currentTarget.dataset.pay).toFixed(2)
    })
    this.getMoneyTotal()
  },

  // 确认送达弹窗
  onConfirmlOrder: function (e) {
    sendOrderNo = e.currentTarget.dataset.no;
    this.setData({
      showConfirm: true
    })
  },

  // 关闭确认送达
  closeSendWin: function () {
    this.setData({
      showConfirm: false
    })
  },

  // 确认送达
  onSendHandle: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/order/mall/confirm',
      data: {
        token: wx.getStorageSync('token'),
        order_no: sendOrderNo
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          wx.showToast({
            title: '确认收货成功！',
            duration: 800
          })
          that.setData({
            showConfirm: false,
            cloudList: []
          })
          that.getCloudList();
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 800
          })
        }
      }, fail() {
        wx.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 800
        })
      }
    })
  }

})